package com.libgdxbar.pvzlikegame.asset;


import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;

import java.util.Objects;

public class AssetBatch {
    private final Array<AssetExecution> executions;

    private AssetBatch(Array<AssetExecution> executions) {
        this.executions = executions;
    }

    public Array<AssetExecution> getExecutions() {
        return executions;
    }

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder {
        private final Array<AssetExecution> executions;

        private static String[] assetPaths;

        public Builder() {
            executions = new Array<>();
        }

        /**
         * 添加单个资源
         *
         * @param fileName 资源文件名
         * @param type     资源类型
         * @return
         */
        public Builder add(String fileName, Class<?> type) {
            executions.add(new AssetExecution(fileName, type, null));
            return this;
        }

        /**
         * 根据正则表达式批量添加资源
         *
         * @param regex 正则表达式
         * @param type  资源类型
         * @return
         */
        public Builder pattern(String regex, Class<?> type) {
            String[] assetPaths = getAssetPaths();
            for (String assetPath : assetPaths) {
                if (Objects.isNull(assetPath) || assetPath.isEmpty()) {
                    continue;
                }
                if (assetPath.matches(regex)) {
                    executions.add(new AssetExecution(assetPath, type, null));
                }
            }
            return this;
        }

        /**
         * 获取资源清单路径
         *
         * @return 资源清单路径
         */
        private static String[] getAssetPaths() {
            if (Objects.nonNull(assetPaths)) {
                return assetPaths;
            }
            FileHandle assetFileHandle = Gdx.files.internal("assets.txt");
            String assetManifestText = assetFileHandle.readString();
            assetPaths = assetManifestText.split("\n");
            return assetPaths;
        }

        public AssetBatch build() {
            return new AssetBatch(executions);
        }
    }
}
